#!/usr/bin/env python
import httplib
import datetime
import traceback
import thread
from time import sleep
testurl='http://www.baidu.com'
print_lock=thread.allocate_lock();
def contime(url,proxyip="127.0.0.1",proxyport=8080,timeout=10):
  a = datetime.datetime.now();
  h1=httplib.HTTPConnection(proxyip,proxyport,timeout=timeout);
  h1.putrequest('GET',url);
  h1.endheaders();
  r1=h1.getresponse();
  g1=r1.getheaders();
  g1=r1.read();
  h1.close();
  b = datetime.datetime.now();
#  print "proxy:%s:%d"%(proxyip,proxyport)
  return str(r1.status)+' '+str(r1.reason)+' '+"time:%s"%(str(b-a))
  
astr="""
while(True):
  try:
    sleep(0.2);
  except:
    try:

    except timeout:
      print "it costs more than 10s"
    except:
      traceback.print_exc();
"""
print "start to connet",testurl
isstop=0;
success=0;
fail=0;
def thr_test(*nothing):
  global success,fail
  thrid=nothing[0]
  while(True):
    try:
      if (isstop==1):return;
      sleep(1);
      restr=contime(testurl);
      print_lock.acquire()
      print str(datetime.datetime.now())+"  T:%3d"%(thrid)+' '+restr
      print_lock.release()
      success+=1;
#    except timeout:
#      print_lock.acquire()
#      print "it costs more than 10s"
#      print_lock.release()
    except:
      fail+=1;
      print_lock.acquire()
      traceback.print_exc(); 
      print_lock.release() 
    sleep(1)
for x in xrange(0,10):
  print "thread:",x
  thread.start_new_thread(thr_test,(x,));

try:
  while(True):
    sleep(100)
except:
  print "success:%d fail:%d fail per:%0.3f%%"%(success,fail,fail/(0.0+success+fail))
  
  

